//解决click三号秒延迟
FastClick.attach(document.body);

let myAudio = document.querySelector("#myAudio"),
    //获得按钮
    musicBtn = document.querySelector(".music-btn"),
    titleBox = document.querySelector('.base-info .title'),
    authorBox = document.querySelector('.base-info .author'),
    wrapperBox = document.querySelector(".wrapper"),
    lyricList = [],
    alreadBox = document.querySelector('.already'),
    durationBox = document.querySelector(".duration"),
    rateBox = document.querySelector(".rate")

//处理播放时间和进度的
const format = function format(num) {
    let minutes = Math.floor(num / 60),
        seconds = Math.ceil(num - minutes * 60);
    if (minutes < 10) minutes = "0" + minutes;
    if (seconds < 10) seconds = "0" + seconds;
    return `${minutes}:${seconds}`
};
//currentTime 播放时间
//duration 总时间
const handleTimeAndRate = function handleTimeAndRate() {
    let { currentTime, duration } = myAudio;

    if (isNaN(currentTime) || isNaN(duration)) return;
    if (currentTime > duration) {
        currentTime = 0;
    }
    alreadBox.innerHTML = format(currentTime);
    durationBox.innerHTML = format(duration);
    rateBox.style.width = `${currentTime / duration * 100}%`


}
//等待audio加载完毕基础信息：绑定总时间等
myAudio.onloadedmetadata = handleTimeAndRate
$sub.on('music', handleTimeAndRate);

//获取歌词绑定数据
const render = function render(lyric) {
    //解析出标题和作者
    let title = lyric.match(/\[ti&#58;([^\]]+)\]/),
        author = lyric.match(/\[ar&#58;([^\]]+)\]/);
    if (title) titleBox.innerHTML = title[1];
    if (author) authorBox.innerHTML = author[1];

    //num第一次匹配拿的内容
    //解析歌词
    let arr = [];
    
    lyric.split('\n')
    lyric.replace(/\[(\d+):(\d+).(?:\d+)\]([^/\n]+)/g, (_, minutes, seconds, text) => {
        console.log(minutes, seconds, text);
        arr.push({
            minutes, seconds, text
        })
    });


    //歌词锁定
    let str = ``
    arr.forEach(item => {
        let { minutes, seconds, text } = item;
        str += `<p minutes="${minutes}" seconds="${seconds}">
            ${text}
        </p >`;
    })
    wrapperBox.innerHTML = str;
    //其他操作
    musicBtn.style.display = 'block'
    //获取歌词绑定歌词
    lyricList = Array.from(wrapperBox.querySelectorAll('p'));
};

const queryData = function queryData() {
    return new Promise(resolve => {
        let xhr = new XMLHttpRequest;
        xhr.open('GET', './json/lyric.json');
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4 && xhr.status === 200) {
                let data = JSON.parse(xhr.responseText);
                resolve(data);
            }
        };
        xhr.send();
    });
};
//  第二个then拿到的就只有歌词
queryData()
    .then(value => {
        return value.lyric;
    })
    .then(lyric => {
        render(lyric)
    })
//  播放暂停  控制歌词
let n = 0;
$sub.on('music', function () {
    let { currentTime, duration } = myAudio,
    [minutes, seconds] = format(currentTime).split(':'),
    H = lyricList[0].offsetHeight;
// 从所有歌词中筛选出：和播放时间匹配的歌词集合 & 不匹配的集合
// 一经发现匹配再处理
let matchArr = [],
    matchNoneArr = [];
lyricList.forEach(item => {
    let a = item.getAttribute('minutes'),
        b = item.getAttribute('seconds');
    if (a === minutes && b === seconds) {
        matchArr.push(item);
        return;
    }
    matchNoneArr.push(item);
});
if (matchArr.length > 0) {
    matchArr.forEach(item => item.classList.add('active'));
    matchNoneArr.forEach(item => item.classList.remove('active'));
    // 匹配的同时不要忘记：WRAPPER的挪动
    n += matchArr.length;
    if (n > 4) {
        wrapperBox.style.transform = `translateY(${-(n - 4) * H}px)`;
    }

    }
    //播放完毕
    if (currentTime >= duration) {
        myAudio.pause();
        musicBtn.classList.remove('move');
        wrapperBox.style.transform = `translateY(0)`;
        
        // wrapperBox.style.transform = `translateY(0)`;
        lyricList.forEach(item => item.classList.remove('active'));
        n=0;
        if (timer) {
            clearInterval(timer)
            timer = null
        }
    }

})
let timer = null;
musicBtn.onclick = function () {
    if (myAudio.paused) {
        myAudio.play();
        musicBtn.classList.add('move');
        if (!timer) {
            $sub.emit('music');

            timer = setInterval(() => {
                $sub.emit('music')

            }, 1000)
        }
        return;
    }
    myAudio.pause();
    musicBtn.classList.remove('move');
    if (timer) {
        clearInterval(timer)
        timer = null;
    }
}